<template>
  <view class="location-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 接单位置设置 -->
    <view class="section-card">
      <view class="section-header">
        <text>接单位置</text>
        <text class="sub-title">用于计算往返距离</text>
      </view>
      <view class="location-setting" @tap="setLocation">
        <text class="iconfont icon-location warning" v-if="!location"></text>
        <text class="warning-text" v-if="!location">暂未设置，可能导致无法接单</text>
        <text v-else>{{ location }}</text>
        <text class="iconfont icon-arrow-right"></text>
      </view>
    </view>

    <!-- 服务半径设置 -->
    <view class="section-card">
      <view class="section-header">
        <text>服务半径</text>
        <text>(km)</text>
      </view>
      <view class="radius-setting">
        <view class="radius-control">
          <text class="control-btn" @tap="decreaseRadius">-</text>
          <input 
            type="number" 
            v-model="serviceRadius" 
            class="radius-input"
            @input="onRadiusInput"
          />
          <text class="control-btn" @tap="increaseRadius">+</text>
        </view>
      </view>
    </view>

    <!-- 地图展示 -->
    <view class="map-section">
      <map
        class="map"
        :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude"
        :markers="markers"
        :circles="circles"
        :scale="12"
      ></map>
      <view class="map-legend">
        <view class="legend-item">
          <view class="dot blue"></view>
          <text>接单位置</text>
        </view>
        <view class="legend-item">
          <view class="circle pink"></view>
          <text>服务范围</text>
        </view>
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-btn">
      <button class="save-btn" @tap="saveLocationSettings">保存设置</button>
    </view>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
  data() {
    return {
      location: '',
      serviceRadius: 0,
      mapCenter: {
        latitude: 39.908692,
        longitude: 116.397477
      },
      markers: [],
      circles: [],
      techId: null,
      isLoading: true
    }
  },

  onLoad() {
    // 从缓存中获取技师ID
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.techId) {
      this.techId = userInfo.techId;
      console.log('技师ID:', this.techId);
    } else {
      console.error('未找到技师ID');
    }
    
    // 加载技师位置信息
    this.loadTechnicianLocation();
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },

    openLocationSetting() {
      uni.openSetting({
        success: (res) => {
          console.log(res.authSetting)
        }
      })
    },

    goToTrainingRecords() {
      uni.navigateTo({
        url: '/pages/technician/training-records'
      })
    },

    async setLocation() {
      try {
        const res = await uni.chooseLocation({
          success: (res) => {
            this.location = res.longitude
            this.mapCenter.latitude = res.latitude
            this.mapCenter.longitude = res.longitude
            this.updateMapOverlays()
          }
        })
      } catch (err) {
        uni.showToast({
          title: '请授权位置权限',
          icon: 'none'
        })
      }
    },

    decreaseRadius() {
      if (this.serviceRadius > 0) {
        this.serviceRadius--
        this.updateMapOverlays()
      }
    },

    increaseRadius() {
      if (this.serviceRadius < 20) {
        this.serviceRadius++
        this.updateMapOverlays()
      }
    },

    onRadiusInput(e) {
      const value = parseInt(e.detail.value)
      if (value >= 0 && value <= 20) {
        this.serviceRadius = value
        this.updateMapOverlays()
      }
    },

    updateMapOverlays() {
      // 更新标记点
      this.markers = [{
        id: 1,
        latitude: this.mapCenter.latitude,
        longitude: this.mapCenter.longitude,
        iconPath: '/static/icons/location.png',
        width: 32,
        height: 32
      }]

      // 更新服务范围圆圈
      this.circles = [{
        latitude: this.mapCenter.latitude,
        longitude: this.mapCenter.longitude,
        radius: this.serviceRadius * 1000,
        fillColor: '#FF69B440',
        strokeColor: '#FF69B4',
        strokeWidth: 2
      }]
    },
    
    // 首先加载技师位置信息
    async loadTechnicianLocation() {
      if (!this.techId) {
        // 如果没有技师ID，直接加载位置设置
       // this.loadLocationSettings();
	   uni.showToast({
	     title: '请登录',
	     icon: 'none'
	   })
        return;
      }
      
      uni.showLoading({
        title: '加载中...'
      });
      
      try {
        // 调用获取技师详细信息的API
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/technician/technician/${this.techId}`,
          method: 'GET',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (result.data.code === 200 && result.data.data) {
          const techData = result.data.data;
          console.log('获取到的技师信息:', techData);
          
          // 如果技师信息中包含位置数据
          if (techData.longitude && techData.latitude) {
            console.log('使用技师信息中的位置数据');
            
            // 设置地图中心点为技师位置
            this.mapCenter.latitude = techData.latitude;
            this.mapCenter.longitude = techData.longitude;
			this.location =    techData.longitude;
			this.serviceRadius = techData.radius || 0
            
            // 如果有地址信息，也一并设置
            if (techData.address) {
              this.location = techData.address;
            }
            
            // 更新地图标记和圆圈
            this.updateMapOverlays();
          }
        }
        
        // 无论是否从技师信息中获取到位置数据，都继续加载位置设置
        // 如果位置设置中有数据，将会覆盖技师信息中的数据
        // this.loadLocationSettings();
        
      } catch (err) {
        console.error('获取技师位置信息失败:', err);
        // 出错时，仍然尝试加载位置设置
      //  this.loadLocationSettings();
      } finally {
        uni.hideLoading();
      }
    },

    async loadLocationSettings() {
      try {
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/member/location-settings`,
          method: 'GET',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        })

        if (result.data.code === 200) {
          const { location, radius, latitude, longitude } = result.data.data
          
          // 只有在有效的位置数据时才更新
          if (location && latitude && longitude) {
            this.location = location
            this.serviceRadius = radius || 0
            this.mapCenter.latitude = latitude
            this.mapCenter.longitude = longitude
            this.updateMapOverlays()
          }
        }
      } catch (err) {
        console.error('加载位置设置失败:', err)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false;
      }
    },

    async saveLocationSettings() {
      if (!this.location) {
        uni.showToast({
          title: '请设置接单位置',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({
          title: '保存中...'
        });
        
        // const result = await uni.request({
        //   url: `${uni.$config.baseUrl}/member/location-settings`,
        //   method: 'POST',
        //   header: {
        //     'Authorization': uni.getStorageSync('token')
        //   },
        //   data: {
        //     location: this.location,
        //     radius: this.serviceRadius,
        //     latitude: this.mapCenter.latitude,
        //     longitude: this.mapCenter.longitude
        //   }
        // })

        // if (result.data.code === 200) {
          // 同时更新技师表中的位置信息
          await this.updateTechnicianLocation();
          
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        // } else {
        //   uni.showToast({
        //     title: result.data.message || '保存失败',
        //     icon: 'none'
        //   })
        // }
      } catch (err) {
        console.error('保存位置设置失败:', err);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading();
      }
    },
    
    // 更新技师表中的位置信息
    async updateTechnicianLocation() {
      if (!this.techId) return;
	  
	  console.log("this.serviceRadius",this.serviceRadius)
      
      try {
        // 先获取技师当前信息
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/technician/technician/${this.techId}`,
          method: 'GET',
          header: {
            'Authorization': uni.getStorageSync('token')
          }
        });
        
        if (result.data.code === 200 && result.data.data) {
          const techData = result.data.data;
          
          // 更新技师信息，仅更新位置相关字段
          const updateResult = await uni.request({
            url: `${uni.$config.baseUrl}/technician/technician`,
            method: 'PUT',
            header: {
              'Authorization': uni.getStorageSync('token'),
              'Content-Type': 'application/json'
            },
            data: {
              // ...techData,
			  id: this.techId,
              latitude: this.mapCenter.latitude,
              longitude: this.mapCenter.longitude,
              address: this.location,
			  radius: this.serviceRadius
            }
          });
          
          if (updateResult.data.code === 200) {
            console.log('技师位置信息更新成功');
          } else {
            console.error('技师位置信息更新失败:', updateResult.data.msg);
          }
        }
      } catch (err) {
        console.error('更新技师位置信息失败:', err);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.location-container {
  min-height: 100vh;
  background: #F8F8F8;
  padding-bottom: 120rpx; /* 为底部按钮留出空间 */

  .custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 88rpx;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    z-index: 100;
    border-bottom: 1rpx solid #F5F5F5;
    
    .left {
      width: 88rpx;
      display: flex;
      align-items: center;
      
      .iconfont {
        font-size: 36rpx;
        color: #333333;
      }
    }
    
    .center {
      flex: 1;
      text-align: center;
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
    }

    .right {
      width: 120rpx;
      display: flex;
      justify-content: flex-end;

      text {
        font-size: 28rpx;
        color: #2B85E4;
      }
    }
  }

  .section-card {
    margin-top: 20rpx;
    background: #FFFFFF;
    padding: 30rpx;

    .section-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;

      text {
        font-size: 32rpx;
        color: #333333;

        &.sub-title {
          font-size: 24rpx;
          color: #999999;
        }
      }

      .view-all {
        display: flex;
        align-items: center;
        gap: 4rpx;

        text {
          font-size: 28rpx;
          color: #2B85E4;

          &.iconfont {
            font-size: 24rpx;
          }
        }
      }
    }

    .location-setting {
      display: flex;
      align-items: center;
      gap: 10rpx;
      padding: 20rpx;
      background: #F8F8F8;
      border-radius: 8rpx;

      .warning {
        color: #FF6B6B;
      }

      .warning-text {
        font-size: 28rpx;
        color: #FF6B6B;
      }

      .iconfont {
        font-size: 28rpx;
        color: #999999;
      }
    }

    .radius-setting {
      .radius-control {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 20rpx;

        .control-btn {
          width: 80rpx;
          height: 80rpx;
          background: #F8F8F8;
          border-radius: 8rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 36rpx;
          color: #333333;
        }

        .radius-input {
          width: 200rpx;
          height: 80rpx;
          background: #F8F8F8;
          border-radius: 8rpx;
          text-align: center;
          font-size: 32rpx;
          color: #333333;
        }
      }
    }
  }

  .map-section {
    margin: 20rpx;
    border-radius: 12rpx;
    overflow: hidden;
    position: relative;

    .map {
      width: 100%;
      height: 600rpx;
    }

    .map-legend {
      position: absolute;
      right: 20rpx;
      bottom: 20rpx;
      background: rgba(255, 255, 255, 0.9);
      padding: 16rpx;
      border-radius: 8rpx;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 8rpx;
        margin-bottom: 8rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .dot {
          width: 16rpx;
          height: 16rpx;
          border-radius: 50%;

          &.blue {
            background: #2B85E4;
          }
        }

        .circle {
          width: 16rpx;
          height: 16rpx;
          border-radius: 50%;
          border: 2rpx solid #FF69B4;

          &.pink {
            background: rgba(255, 105, 180, 0.25);
          }
        }

        text {
          font-size: 24rpx;
          color: #666666;
        }
      }
    }
  }
  
  .bottom-btn {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx 30rpx;
    background: #FFFFFF;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .save-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      background: #FF4B4B;
      color: #FFFFFF;
      font-size: 32rpx;
      font-weight: 500;
      border-radius: 45rpx;
      text-align: center;
    }
  }
}
</style> 